from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.urls import reverse
from myadmin.views import OpenStackToken

# Create your views here.

import requests,json,time

import os
from pathlib import Path

import myadmin.views.OpenStackToken

# 导入日志处理模块
import logging
# -----------logger-----------
# get logger
logger = logging.getLogger(__name__)
# level
logger.setLevel(logging.DEBUG)
# format
format = logging.Formatter('%(asctime)s %(message)s')
# to console
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(format)
logger.addHandler(stream_handler)
# -----------logger-----------


url = OpenStackToken.imageurl
headers = OpenStackToken.getToken()

def index(request):
    # 通过render方法让html模板喧染页面
    imagelist = json.loads(requests.get(url, headers=headers).text)
    datadict=[]

    for image in imagelist['images']:
        imageid = image['id']
        owner = image['owner']

        # 可以根据owner获取所有者
        #根据id获取每一个image的详细值
        # url_detail = url+"/"+flavorid
        # flavordetail = json.loads(requests.get(url_detail, headers=headers).text)['flavor']
        # #print(flavordetail)
        # temp = {"id":flavorid,"name":flavor['name'],"ram":flavordetail['ram'],"vcpus":flavordetail['vcpus'],"disk":flavordetail['disk'],"swap":flavordetail['swap']}
        # datadict.append(temp)

    #print(datadict)
    context = {"imagelist": imagelist["images"]}
    return render(request,"myadmin/image/index.html",context)

def add(request):
    '''加载添加信息'''
    return render(request, "myadmin/image/imageadd.html")

def insert(request):
    '''执行信息添加'''
    try:
        imagename = request.POST['imagename']
        imagediskformat = request.POST['imagediskformat']
        # 获取上传文件
        obj = request.FILES.get('imagefile')

        print(obj.name)

        # 暂存文件至服务器目录
        # 上传到openstack中会默认存放在/var/lib/glance/images目录下
        imagefile = saveFile(obj)

        # 生成http提交时的body数据
        body = {
                "name": imagename,
                "container_format": "bare",
                "disk_format": imagediskformat,
            }

        response = requests.post(url, data=json.dumps(body), headers=headers)

        logger.debug(response.status_code)
        #print("返回结果：" + str(response.status_code))
        if response.status_code == 201:
            imageid  = json.loads(response.text)['id']
            #调用方法上传镜像文件
            status = upload_image_data(imageid,imagefile)
            if status == 204:
                return redirect(reverse("myadmin_image_index"))
            else:
                return HttpResponse("出错啦：上传镜像文件失败！！" )
        else:
            return HttpResponse("出错啦：" + response.text)
    except Exception as err:
        return HttpResponse("出错啦："+str(err))


def delete(request,id=""):
    url_delete = url + "/" + id

    try:
        response = requests.delete(url_delete, headers=headers)
        return redirect(reverse("myadmin_image_index"))
    except Exception as err:
        return HttpResponse("是出错啦：" + str(err))

def edit(request,id=0):
    try:
        # 通过render方法让html模板喧染页面
        resurl = url + "/" + str(id)
        headers = OpenStackToken.getToken()

        image = json.loads(requests.get(resurl, headers=headers).text)

        if image:
            context = {"image": image}
            print(context)
            return render(request, "myadmin/image/imageedit.html", context)
        else:
            return HttpResponse("未找到该镜像信息！！")
    except Exception as err:
        return HttpResponse("是出错啦：" + str(err))


def update(request):
     '''执行编辑信息'''
     name = request.POST['imagename']
     imageid = request.POST['imageid']
     strValue = request.POST['ragrp1']
     protected = True
     if strValue == "0":
         protected = False

     body = [
               {
                    "op": "replace",
                    "path": "/name",
                    "value": name
                },
                 {
                     "op": "replace",
                     "path": "/protected",
                     "value": protected
                 }
            ]

     #print(body)

     try:
         resurl = url + "/" + str(imageid)
         headers['Content-Type'] = "application/openstack-images-v2.1-json-patch"
         status_code = requests.patch(resurl,data=json.dumps(body), headers=headers).text
         #print(status_code)
         jumpurl = reverse("myadmin_image_index")
         return redirect(jumpurl+"?index=2")
     except Exception as err:
         return HttpResponse("是出错啦：" + str(err))


#  获取Glance ID
def get_image_id( image_name: str):
    result = json.loads(requests.get(url, headers=headers).text)
    for item in result['images']:
        if (item['name'] == image_name):
            return item['id']


# 上传glance镜像
# Image data¶ Uploads and downloads raw image data.
# These operations may be restricted to administrators. Consult your cloud operator’s documentation for details.
# /v2/images/{image_id}/file
# 镜像可以重名
def upload_image_data(image_id: str, file_path=""):
    """
    :param image_id:
    :param file_path:
    :return:
     """
    resUrl = url + "/" + image_id + "/file"
    headers['Content-Type'] = "application/octet-stream"
    response = requests.put(resUrl, data=open(file_path, 'rb').read(), headers=headers)
    #if response.status_code == 204:
    #    return {"ImageItemCreatedSuccess": response.status_code}
    return response.status_code

#  上传文件至static/uploadfile下
def saveFile(obj: object):
    BASE_DIR = Path(__file__).resolve().parent.parent
    filepath = os.path.join(BASE_DIR,'uploadfile',obj.name)
    #print("filepath="+filepath)
    f = open(filepath,'wb')
    for chunk in obj.chunks():
        f.write(chunk)
    f.close()
    return filepath

